package cn.fastoo.common.dao.system;


import cn.fastoo.common.entity.system.AdminSystemMenu;
import cn.fastoo.common.sampleframe.dao.FastDao;
import cn.fastoo.common.sampleframe.dao.impl.FastDaoImpl;
import cn.fastoo.common.sampleframe.search.Search;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Component
public class AdminSystemMenuDao extends FastDaoImpl<AdminSystemMenu> implements FastDao<AdminSystemMenu> {

    public Logger logger = LoggerFactory.getLogger(AdminSystemMenuDao.class);

    @Autowired
    @Qualifier("mainDS")
    private void setJt(DataSource ds){
        this.jt = new JdbcTemplate(ds);
    }

    private List<AdminSystemMenu> systemMenus = null;

    @Scheduled(cron = "0/5 * * * * ?")
    private void init(){
        List<AdminSystemMenu> dbData = find(new Search());

        Map<Long,List<AdminSystemMenu>> groupByPidMap = dbData.stream().collect(Collectors.groupingBy(AdminSystemMenu::getPid));

        List<AdminSystemMenu> topLevel = groupByPidMap.get(Long.valueOf(0));

        for(int i =0 ;i<topLevel.size();i++){
            AdminSystemMenu top = topLevel.get(i);

            top.setChildren(new LinkedList<AdminSystemMenu>());
            List<AdminSystemMenu> children = treeLize(top.getId(),groupByPidMap);
            if(children!=null){
                top.getChildren().addAll(children);
            }

        }
        systemMenus = topLevel;

    }
    public static List<AdminSystemMenu> treeLize(Long topId,Map<Long,List<AdminSystemMenu>> groupByRidMap){
        if(groupByRidMap.get(topId)==null){
            return  null;
        }
        List<AdminSystemMenu> children = groupByRidMap.get(topId);
        for(int i =0 ;i<children.size();i++){
            AdminSystemMenu node = children.get(i);
            node.setChildren(treeLize(node.getId(),groupByRidMap));
        }
        return children;
    }
    public List<AdminSystemMenu> getTree(){
        return systemMenus;
    }
}
